package com.trainingcloud;

import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;

import com.trainingcloud.exception.SystemException;

public class TokenManager 
{
	private Hashtable<Integer, Token> tokenHash;
	
	public TokenManager()
	{
		tokenHash = new Hashtable<Integer, Token>();
	}
	
	public String generateOneToken(int userId)
	{
		UUID uuid = UUID.randomUUID();
		Token token = new Token();
		token.setUserId(userId);
		token.setToken(uuid.toString());
		token.setLatestTime(new Date());
		tokenHash.put(userId, token);
		return token.getToken();
	}
	
	public int checkToken(String token)
	{
		Iterator i = tokenHash.entrySet().iterator();
		while(i.hasNext())
		{
			Entry entry = (Entry)i.next();
			Token obj = (Token)(entry.getValue());
			if(obj.getToken().compareTo(token)==0)
			{
				Date now = new Date();
				if(now.getTime()-obj.getLatestTime().getTime()<1000*60*60*10)
				{
					return obj.getUserId();
				}
			}
		}
		return -1;
	}
	
	public void releaseToken(int userId)
	{
		if(tokenHash.contains(userId))
		{
			tokenHash.remove(userId);
		}
	}
	
	public void renewToken(int userId)
	{
		Token token = tokenHash.get(userId);
		token.setLatestTime(new Date());
		tokenHash.put(userId, token);
	}
}
